<?php
/**
 * ----------------------------------------------------------------------------
 * 文件名称：wxjspay.php
 * ----------------------------------------------------------------------------
 * 功能描述：手机微信支付插件
 * ----------------------------------------------------------------------------
 */

/* 访问控制 */
defined('IN_ECTOUCH') or die('Deny Access');

$payment_lang = ROOT_PATH . 'plugins/payment/language/' . C('lang') . '/' . basename(__FILE__);

if (file_exists($payment_lang)) {
    include_once ($payment_lang);
    L($_LANG);
}
/* 模块的基本信息 */
if (isset($set_modules) && $set_modules == TRUE) {
    $i = isset($modules) ? count($modules) : 0;
    /* 代码 */
    $modules[$i]['code'] = basename(__FILE__, '.php');
    /* 描述对应的语言项 */
    $modules[$i]['desc'] = 'wxjspay_desc';
    /* 是否支持货到付款 */
    $modules[$i]['is_cod'] = '0';
    /* 是否支持在线支付 */
    $modules[$i]['is_online'] = '1';
    /* 作者 */
    $modules[$i]['author'] = 'SUNNT-TECH TEAM';
    /* 网址 */
    $modules[$i]['website'] = 'http://www.sunny-tech.com';
    /* 版本号 */
    $modules[$i]['version'] = '1.0.0';
    /* 配置信息 */
    $modules[$i]['config'] = array(
        array(
            'name' => 'wxjspay_app_id',
            'type' => 'text',
            'value' => ''
        ),
        array(
            'name' => 'wxjspay_app_secret',
            'type' => 'text',
            'value' => ''
        ),
        array(
            'name' => 'wxjspay_mchid',
            'type' => 'text',
            'value' => ''
        ),
        array(
            'name' => 'wxjspay_key',
            'type' => 'text',
            'value' => ''
        ),
        array(
            'name' => 'relate_pay',
            'type' => 'select',
            'value' => ''
        )
    );
    
    return;
}

define('WXPAY_ROOT_PATH', realpath(ROOT_PATH . '../') . '/');
include_once(WXPAY_ROOT_PATH . "wxpay/jsapi/WxPay.JsApiPay.php");
require_once WXPAY_ROOT_PATH . "wxpay/log.php";//初始化日志
/**
 * 支付插件类
 */
class wxjspay
{

    /**
     * 生成支付代码
     *
     * @param array $order
     *            订单信息
     * @param array $payment
     *            支付方式信息
     */
    function get_code($order, $payment)
    {
        if (! defined('EC_CHARSET')) {
            $charset = 'utf-8';
        } else {
            $charset = EC_CHARSET;
        }
        if (!$this->isWeChat()) {
            return '<button type="button" class="btn btn-info ect-btn-info ect-colorf ect-bg disabled">请用微信浏览器或更换其他支付方式</button>';
        }
        WxPayConfig::setValue('appid', $payment['wxjspay_app_id']);
        WxPayConfig::setValue('appsecret', $payment['wxjspay_app_secret']);
        WxPayConfig::setValue('mchid', $payment['wxjspay_mchid']);
        WxPayConfig::setValue('key', $payment['wxjspay_key']);
        
        $fee = intval($order['order_amount']  * 100);
        
        //①、获取用户openid
        $tools = new JsApiPay();
        
        $openId = $tools->GetOpenid();
        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody($order['order_sn']);
//        $input->SetAttach("test");
        $input->SetOut_trade_no($order['order_sn'] . "_" . $order['log_id'] . "_" . $fee);
        $input->SetTotal_fee($fee);//付款金额单位：分
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
//        $input->SetGoods_tag("test");
        $input->SetNotify_url( __URL__."/notify.php");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $unifiedOrder = WxPayApi::unifiedOrder($input);
        if ($unifiedOrder['result_code'] == 'FAIL' || $unifiedOrder['return_code'] == 'FAIL') {
            $button = '<button type="button" class="btn btn-info ect-btn-info ect-colorf ect-bg">请选择其它方式支付</button>';
            return $button;
        }
        $jsApiParameters = $tools->GetJsApiParameters($unifiedOrder);
        //获取共享收货地址js函数参数
        //$editAddress = $tools->GetEditAddressParameters();
        $url = url('user/order_detail', array('order_id' => $order['order_id']));
        $jsPayScript = <<<EOT
<script type="text/javascript">
	//调用微信JS api 支付
	function jsApiCall() {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest',
                {$jsApiParameters},
                function(res){
                    if(res.err_msg == 'get_brand_wcpay_request:ok') {
                        location.href = '{$url}';
                    } else {
                        //alert('启动微信支付失败, 请检查你的支付参数. 详细错误为: ' + res.err_msg);
                        location.href = '{$url}';
                    }
                }
            );
	}

	function callpay() {
            if (typeof WeixinJSBridge == "undefined"){
                if( document.addEventListener ){
                    document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
                }else if (document.attachEvent){
                    document.attachEvent('WeixinJSBridgeReady', jsApiCall); 
                    document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
                }
            }else{
                jsApiCall();
            }
	}
        document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
            WeixinJSBridge.call('hideToolbar');
            WeixinJSBridge.call('hideOptionMenu');
	});
	</script>
EOT;
        
        /* 生成支付按钮 */
        $button = $jsPayScript . '<div><button type="button" class="btn btn-info ect-btn-info ect-colorf ect-bg" onclick="callpay()">立即使用微信支付</button></div>';
        return $button;
    }
    private function isWeChat() {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (stripos($user_agent, 'MicroMessenger') !== false) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 同步响应操作
     * 
     * @return string
     */
    public function callback($data)
    {
        return true;
    }
    /**
     * 异步通知
     * 
     * @return string
     */
    public function notify($data)
    {
        $payment = model('Payment')->get_payment($data['code']);
        WxPayConfig::setValue('appid', $payment['wxpay_app_id']);
        WxPayConfig::setValue('mchid', $payment['wxpay_mchid']);
        WxPayConfig::setValue('key', $payment['wxpay_key']);
        
        $logHandler= new CLogFileHandler(WXPAY_ROOT_PATH . "wxpay/logs/".date('Y-m-d').'.log');
        Log::Init($logHandler, 15);
        $input = file_get_contents('php://input');
        if (!preg_match('/(\<\!DOCTYPE|\<\!ENTITY)/i', $input)) {
            libxml_disable_entity_loader(true);
            $obj = simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);
            $data = json_decode(json_encode($obj), true);
            if (empty($data['out_trade_no'])) {
                Log::DEBUG("ERROR:out_trade_no不存在");
                exit('fail');
            }
            list($order_sn, $log_id) = explode('_', $data['out_trade_no']);
            
            $total_fee = ($data['total_fee'] / 100);
            if ( !model('Payment')->check_money( $log_id, $total_fee ) ) {
                Log::DEBUG("订单金额不符");
                exit('fail');
            }
            if ($data['result_code'] == 'SUCCESS' && $data['return_code'] == 'SUCCESS') {
                Log::DEBUG("SUCCESS:" . $data['out_trade_no']);
                /* 改变订单状态 */
                model('Payment')->order_paid($log_id, 2);
                exit('success');
            }else{
                if ($data["return_code"] == "FAIL") {
                    //此处应该更新一下订单状态，商户自行增删操作
                    Log::DEBUG("【通信出错】:{$data['return_msg']}");
                }elseif($data["result_code"] == "FAIL"){
                    //此处应该更新一下订单状态，商户自行增删操作
                    Log::DEBUG("【业务出错】:{$data['err_code']}--{$data['err_code_des']}");
                }
                exit('fail');
            } 
	}
        exit('success');
    }
}
